<template>
	<el-upload 
		class="avatar-uploader" 
		:show-file-list="false"
		:before-upload="beforeAvatarUpload" 
		:http-request="upload"
	>
		<img v-if="displayImageUrl" :src="displayImageUrl" class="avatar">
		<i v-else class="el-icon-plus avatar-uploader-icon"></i>
	</el-upload>
</template>

<style>
	.avatar-uploader .el-upload {
		border: 1px dashed #d9d9d9;
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
	}

	.avatar-uploader .el-upload:hover {
		border-color: #409EFF;
	}

	.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		line-height: 178px;
		text-align: center;
	}
	
	.el-icon-plus::before{
		line-height: 178px;
	}

	.avatar {
		width: 178px;
		height: 178px;
		display: block;
		object-fit: cover;
	}
</style>

<script>
	import { upload } from "@/api/index.js";
	import config from "@/api/config.js";
	import { ElMessage } from "element-plus";
	export default {
		props: {
			// 接收父组件传递的图片URL（用于编辑时显示已有图片）
			imageUrl: {
				type: String,
				default: ''
			}
		},
		data() {
			return {
				localImageUrl: '', // 本地存储新上传的图片URL
				params: {}
			};
		},
		computed: {
			// 计算属性：优先显示新上传的图片，如果没有则显示父组件传递的图片
			displayImageUrl() {
				return this.localImageUrl || this.imageUrl;
			}
		},
		methods: {
			beforeAvatarUpload(file) {
				// 支持更多图片格式
				const isImage = file.type === 'image/jpeg' || 
							   file.type === 'image/png' || 
							   file.type === 'image/gif' ||
							   file.type === 'image/webp';
				const isLt2M = file.size / 1024 / 1024 < 2;

				if (!isImage) {
					ElMessage.error('上传图片只能是 JPG/PNG/GIF 格式!');
					return false;
				}
				if (!isLt2M) {
					ElMessage.error('上传图片大小不能超过 2MB!');
					return false;
				}

				// 设置上传参数
				this.params.file = file;
				this.params.folder = "/upload/product";
				return true;
			},
			async upload() {
				try {
					// 使用 FormData 格式上传
					const formData = new FormData();
					formData.append('file', this.params.file);
					formData.append('folder', this.params.folder);
					
					const result = await upload(formData);
					console.log('上传结果:', result);
					
					if(result.code == 1){
						const env = process.env.NODE_ENV || 'development';
						const apiUrl = config.baseUrl[env];
						const fullImageUrl = apiUrl + result.data;
						
						// 更新本地图片URL用于显示
						this.localImageUrl = fullImageUrl;
						
						// 通知父组件图片URL更新
						this.$emit('getImageUrl', fullImageUrl);
						ElMessage.success('上传成功');
					} else {
						ElMessage.error(result.message || '上传失败');
					}
				} catch (error) {
					console.error('上传错误:', error);
					ElMessage.error('上传失败，请重试');
				}
			}
		},
		watch: {
			// 监听父组件传递的imageUrl变化（比如重置表单时）
			imageUrl: {
				immediate: true,
				handler(newVal) {
					console.log('父组件图片URL更新:', newVal);
					// 如果父组件传递了新的图片URL，清空本地存储（避免编辑时显示旧的上传图片）
					if (newVal) {
						this.localImageUrl = '';
					}
				}
			}
		},
		mounted() {
			console.log('UploadSingle组件挂载，接收到的imageUrl:', this.imageUrl);
		}
	}
</script>